package com.device.api.service.impl;

import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.device.api.entity.PudongDeviceConfig;
import com.device.api.entity.PudongDeviceData;
import com.device.api.entity.enums.QcCodeEnum;
import com.device.api.entity.vo.QcVo;
import com.device.api.mapper.DeviceApiMapper;
import com.device.api.mapper.PudongDeviceConfigMapper;
import com.device.api.r.Result;
import com.device.api.request.DeviceDataSwitchRequest;
import com.device.api.request.DeviceReadDataRequest;

import com.device.api.request.DeviceUploadFrequencyRequest;
import com.device.api.service.ICtWingService;
import com.device.api.service.IDeviceApiService;

import com.device.api.utils.MD5Util;
import com.device.api.utils.MqttClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
@Slf4j
public class DeviceApiServiceImpl implements IDeviceApiService {

    final static String[] array = {"AEF","AFAa","AEC","AFC","AED","AFD","AEG","AFDa","AFDb",
            "AEE","AFAe","AFAf","AAA","AAAa","AAAb","AAAc","AAAd","AHA_1","AHB_1","ADA","ADAc",
            "ADAd","ADB","ADC","AGA","AGAa","AGAb","AGAc","AGAd"};


    @Autowired
    private PudongDeviceConfigMapper pudongDeviceConfigMapper;


    @Autowired
    private ICtWingService iCtWingService;



    @Autowired
    private DeviceApiMapper deviceApiMapper;

    @Autowired
    private MqttClientUtil mqttClientConfig;



    @Override
    public Result<?> updateDeviceDataSwitch(DeviceDataSwitchRequest request) {

        if (request.getDeviceNo() == null) {
            return Result.error("请输入设备编号");
        }
        if (request.getDataSwitch()==null){
            return Result.error("请输入传输开关状态");
        }

        iCtWingService.updateDeviceDataSwitch(request);
        PudongDeviceConfig pudongDeviceConfig = new PudongDeviceConfig();
        UpdateWrapper<PudongDeviceConfig> pudongDeviceConfigUpdateWrapper = new UpdateWrapper<>();
        pudongDeviceConfigUpdateWrapper.eq("device_no",request.getDeviceNo());
        pudongDeviceConfigUpdateWrapper.set("data_switch",request.getDataSwitch());
        pudongDeviceConfigMapper.update(pudongDeviceConfig,pudongDeviceConfigUpdateWrapper);
        if (request.getDataSwitch()==0){
            return Result.OK(request.getDeviceNo()+"启动成功");
        }

        if (request.getDataSwitch()==1){
            return Result.OK(request.getDeviceNo()+"停止成功");
        }



        return null;
    }

    @Override
    public Result<?> updateDeviceUploadFrequency(DeviceUploadFrequencyRequest request) {
        String deviceNo = request.getDeviceNo();
        if (deviceNo == null) {
            return Result.error("请输入设备编号");
        }
        String deviceFrequencyTime = request.getDeviceFrequencyTime();
        if (deviceFrequencyTime ==null){
            return Result.error("请输入传输时间");
        }
        String deviceFrequencyTimeUnit = request.getDeviceFrequencyTimeUnit();
        if (deviceFrequencyTimeUnit==null){
            return Result.error("请输入传输时间单位" +
                    "");
        }
        iCtWingService.updateDeviceUploadFrequency(request);

        PudongDeviceConfig pudongDeviceConfig = new PudongDeviceConfig();
        UpdateWrapper<PudongDeviceConfig> pudongDeviceConfigUpdateWrapper = new UpdateWrapper<>();
        pudongDeviceConfigUpdateWrapper.eq("device_no",deviceNo);
        pudongDeviceConfigUpdateWrapper.set("reported_time",deviceFrequencyTime);
        pudongDeviceConfigUpdateWrapper.set("reported_time_unit",deviceFrequencyTimeUnit);
        pudongDeviceConfigMapper.update(pudongDeviceConfig,pudongDeviceConfigUpdateWrapper);

        return Result.OK("修改"+ deviceNo +"传输时间为"+deviceFrequencyTime+deviceFrequencyTimeUnit);
    }

    public Result<?> insert(PudongDeviceConfig pudongDeviceConfig){
        return iCtWingService.deviceAddCtWing(pudongDeviceConfig);
    }

    @Override
    public Result<?> delete(String deviceNo) {
        return iCtWingService.deviceDeleteCtWing(deviceNo);
    }

    @Override
    public Result<?> timeCalibration(Object deviceNo) {

        if (deviceNo == null) {
            return Result.error("请输入设备编号");
        }



        return  iCtWingService.setTimeCalibration( deviceNo);
    }

    @Override
    public Result<?> getDeviceTime(Object deviceNo) {
        if (deviceNo == null) {
            return Result.error("请输入设备编号");
        }

        return  iCtWingService.getDeviceTime( deviceNo);
    }

    @Override
    public Result<?> deviceReadData(DeviceReadDataRequest request) {

        return iCtWingService.deviceReadData(request);
    }

    @Override
    public Result<?> deviceSetIp(JSONObject jsonObject) {

        Object deviceNo = jsonObject.get("deviceNo");
        if (deviceNo == null) {
            return Result.error("请输入设备编号");
        }
        Object ip = jsonObject.get("ip");
        if (ip ==null){
            return Result.error("请输入IP地址");
        }





        return  iCtWingService.setDeviceIp(deviceNo,ip);
    }


    @Override
    public JSONObject deviceAuth(JSONObject message) {
        JSONObject result =new  JSONObject();
        Object childId = message.get("clientid");
        Object username = message.get("username");
        Object password = message.get("password");

      if (childId.equals(mqttClientConfig.getClientId())&&username.equals(mqttClientConfig.getUsername())&&password.equals(mqttClientConfig.getPassword()))
      {
          result.set("result", "allow");
          log.info("管理员登录");
          return result;
      }

        PudongDeviceConfig pudongDeviceConfig = pudongDeviceConfigMapper.selectList(new QueryWrapper<PudongDeviceConfig>().eq("device_no", childId)).get(0);
        boolean isChildId =pudongDeviceConfig!=null;
        String md5Encode ="";
        if (isChildId) {
            md5Encode=  MD5Util.MD5Encode(pudongDeviceConfig.getDeviceCtwingId(), null);
        }
        boolean  isUsername = username.equals(pudongDeviceConfig.getImei());
        boolean isPassword =  password.equals(md5Encode);
        if (isChildId && isPassword && isUsername) {
            result.set("result", "allow");
        }else {
            result.set("result", "ignore");
        }


        return result;
    }


    @Override
    public Page<QcVo> deviceQcExaminingReport(String deviceNo, Integer pageNo, Integer pageSize, String startTime, String endTime) {
        Page<QcVo> page = new Page<>();

        List<PudongDeviceData> deviceData = deviceApiMapper.findDeviceData(deviceNo, startTime, endTime);
        Map<String, String> deviceNameMap = getDeviceNameMap(deviceData.stream().map(PudongDeviceData::getDeviceNo).collect(Collectors.toList()));
        List<QcVo> list = new LinkedList<>();
        for (PudongDeviceData deviceDatum : deviceData) {
            QcVo qcVo = new QcVo();
            qcVo.setDeviceNo(deviceDatum.getDeviceNo());
            String name =deviceNameMap.get(deviceDatum.getDeviceNo());
            qcVo.setDataId(deviceDatum.getId());
            qcVo.setDeviceName(name);
            qcVo.setCreateTime(deviceDatum.getCreateTime());
            String qc = deviceDatum.getQC();
            int length = qc.length();
            if (length==29){
                for (int i = 0; i < length; i++) {
                    int start = i * 1;
                    int end = Math.min(start + 1, qc.length());
                    String chunk = qc.substring(start, end);
                    qcVo.setColumn(array[i]);

                    if (chunk.equals(QcCodeEnum.ZERO.getCode())){
                         continue;
                    }
                    QcCodeEnum[] values = QcCodeEnum.values();
                    for (QcCodeEnum value : values) {
                     if (chunk.equals( value.getCode())) {
                         qcVo.setQcCode(value.getCode());
                         qcVo.setQcCodeV(value.getV());
                         qcVo.setQcCodeD(value.getD());
                     }
                    }
                    list.add(qcVo);

                }
            }
        }
        if (pageNo!=null && pageSize!=null&& pageNo>0&&pageSize>0){
        //分页
        int size = list.size();
        page.setTotal(size);
        page.setCurrent(pageNo);
        page.setSize(pageSize);
        if (size > 0){
            int start = (pageNo - 1) * pageSize;
            int end = start + pageSize;
            if (end > list.size()) {
                end = list.size();
            }
            List<QcVo> pageList = list.subList(start, end);
            page.setRecords(pageList);
        }
        }else {
            page.setRecords(list);
        }



        return page;
    }



    private Map<String, String> getDeviceNameMap(List<String> collect) {
        Map<String,String> map = new HashMap<>();
        List<PudongDeviceConfig> pudongDeviceConfigs = pudongDeviceConfigMapper.selectList(new QueryWrapper<PudongDeviceConfig>().select("device_no", "name").in("device_no", collect));
        for (PudongDeviceConfig pudongDeviceConfig : pudongDeviceConfigs) {
            map.put(pudongDeviceConfig.getDeviceNo(), pudongDeviceConfig.getName());
        }
        return map;
    }


}
